package wint.help.server.http;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.URI;

import wint.lang.utils.IoUtil;

import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;

public class FileHttpServer {
	
	private HttpServer httpServer;
	
	private int backlog = 5;
	
	private String contentType = "image/jpeg";
	
	public FileHttpServer(int port, String path, final File filePath) throws IOException {
		httpServer = HttpServer.create(new InetSocketAddress(port), backlog);
		addFileContext(path, filePath);
	}
	
	public String getContentType() {
		return contentType;
	}

	public void setContentType(String contentType) {
		this.contentType = contentType;
	}

	public void start() {
		httpServer.start();
	}
	
	public void stop() {
		httpServer.stop(0);
	}
	
	private void addFileContext(String path, final File filePath) {
		HttpHandler httpHandler = new HttpHandler() {

			public void handle(HttpExchange httpExchange) throws IOException {
				try {
					URI uri = httpExchange.getRequestURI();
					String file = uri.getPath();
					File f = new File(filePath, file);
					if (!f.exists()) {
						httpExchange.sendResponseHeaders(404, 0);
						return;
					}
					httpExchange.sendResponseHeaders(200, f.length());
					FileInputStream fis = new FileInputStream(f);
					httpExchange.getResponseHeaders().add("content-type", contentType);
					IoUtil.copy(fis, httpExchange.getResponseBody());
				} finally {
					httpExchange.close();
				}
			}
			
		};
		httpServer.createContext(path, httpHandler);
	}
	
}
